package com.dev.weixin.manager.controllers;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.security.login.beans.LoginUser;
import com.dev.security.login.service.LoginManager;
import com.dev.security.util.DataGrid;
import com.dev.security.util.Response;
import com.dev.weixin.manager.beans.TextTemplate;
import com.dev.weixin.manager.service.ITextTemplateService;

/**
 * @author 飘渺青衣
 * @see
 */
@Controller
@RequestMapping("/weixin/text/")
public class TextTemplateController {

	@Autowired
	private ITextTemplateService textTemplateService;
	
	@Autowired
	private LoginManager loginManager;
	
	@RequestMapping("browse")
	public @ResponseBody DataGrid<TextTemplate> browse(
			HttpServletRequest request, HttpServletResponse response,
			TextTemplate cond, int page, int rows) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		cond.setUser_id(user.getUserId());
		return this.textTemplateService.findPage(cond, page, rows);
	}
	
	@RequestMapping("create")
	public @ResponseBody Response create(
			HttpServletRequest request, HttpServletResponse response,
			TextTemplate text) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		text.setUser_id(user.getUserId());
		text.setCreateTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
		this.textTemplateService.save(text);
		return new Response(true);
	}
	
	@RequestMapping("update")
	public @ResponseBody Response update(
			HttpServletRequest request, HttpServletResponse response,
			TextTemplate text) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		TextTemplate old = this.textTemplateService.findTextTemplate(text.getId(), user.getUserId());
		if(old != null) {
			text.setUser_id(user.getUserId());
			text.setCreateTime(old.getCreateTime());
			this.textTemplateService.save(text);
			return new Response(true);
		}
		return new Response(false, 1);
	}
	
	@RequestMapping("remove")
	public @ResponseBody Response remove(
			HttpServletRequest request, HttpServletResponse response,
			String[] ids) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		int count = this.textTemplateService.remove(ids, user.getUserId());
		return new Response(count > 0, count);
	}
	
}
